package multiDataSource;

import jasperreport.User;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.util.JRLoader;

public class ParameterDataSource implements Servlet{

	@Override
	public void destroy() {
		
	}

	@Override
	public ServletConfig getServletConfig() {
		return null;
	}

	@Override
	public String getServletInfo() {
		return null;
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		
	}

	@Override
	public void service(ServletRequest request, ServletResponse response)
			throws ServletException, IOException {
		
		ServletOutputStream out = response.getOutputStream();
		try {
			
			response.setCharacterEncoding("UTF-8");
			ServletContext servletContext = request.getServletContext();
			//得到jasper文件
			File jasperFile = new File(servletContext.getRealPath("/WEB-INF/classes/multiDataSource/mutilDataSource.jasper"));
			JasperReport jasperReport = (JasperReport)JRLoader.loadObject(jasperFile);
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("crossData", User.getStudent());
			map.put("title", "文章标题");
			JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, new JRBeanCollectionDataSource(User.getStudent()));
			JRXlsExporter exporter = new JRXlsExporter();
			exporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
			exporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, response.getOutputStream());
			exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
			exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);

			HttpServletResponse httpServletResponse = (HttpServletResponse)response;
			httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("asdfasd", "utf-8") + ".xls");
			response.setContentType("application/vnd_ms-excel");
			exporter.exportReport();
		} catch (JRException e) {
			e.printStackTrace();
		} finally {
			
			out.flush();
			out.close();
		}
	}
}
